package BufferedStream1;

import java.io.*;

/**
 * @author: wuhao
 * @since: 2021/5/1 10:16
 */

/**
 *  缓冲流细节分析:
 *     BufferedInputStream:
 *     1. 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区;
 *     2. 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个字节,
 *        存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组;
 *
 *     BufferedOutputStream:
 *     3. 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里,
 *     4. flush()方法的用法: 手动将buffer中内容写入文件
 *
 *     关闭流:
 *     5.关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可，关闭最外层流也会相应关闭内层节点流
 *     6.如果是带缓冲区的流对象的close()方法，不但会关闭流，还会在关闭流之前刷新缓冲区，关闭后不能再写出
 */
public class BufferedInputStreamTest {

    public static void main(String[] args) {
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            //创建节点流
            FileInputStream fileInputStream = new FileInputStream("D:\\test1\\test1.jpg");
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\test2\\test2.jpg");

            //为了提高读写效率,创建处理流 ---> 缓冲流
           bufferedInputStream = new BufferedInputStream(fileInputStream);
           bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            //创建数据临时存储数组
            byte[] data = new byte[1024];
            int length;
            while (((length = bufferedInputStream.read(data)) != -1)) {
                System.out.println(length);
                bufferedOutputStream.write(data, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
